package org.jeecg.modules.api.comApi.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.api.comApi.vo.GetTokenParam;
import org.jeecg.modules.api.comApi.vo.GetTokenRtn;
import org.jeecg.modules.api.comApi.vo.UserSynParam;
import org.jeecg.modules.apiacl.controller.ApiAuthorizeController;
import org.jeecg.modules.apiacl.entity.TaxApiaclAuthorize;
import org.jeecg.modules.apiacl.service.ITaxApiaclAuthorizeService;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


/**
 * @Description: 通用接口管理
 * @Author: jeecg-boot
 * @Date: 2023-08-02
 * @Version: V1.0
 */
@ApiSort(value = 1)
@Api(tags = "通用接口管理")
@RestController
@RequestMapping(CommonConstant.API+"/comApi")
@Slf4j
public class ComApiController extends ApiAuthorizeController {

    @Autowired
    ITaxApiaclAuthorizeService authorizeService;

    @Autowired
    ISysUserService userService;

    @Autowired
    private BaseCommonService baseCommonService;

    @Autowired
    private ISysDepartService departService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取token接口
     *
     * @param tokenParam
     * @return
     */
    @AutoLog(value = "获取token接口")
    @ApiOperation(value = "获取token接口", notes = "获取token接口",position = 1)
    @PostMapping(value = "/getToken")
    public Result<JSONObject> getToken(@RequestBody GetTokenParam tokenParam) {
        log.info(tokenParam.toString());
        TaxApiaclAuthorize authorize = authorizeService.authorize(tokenParam.getApp_key(), tokenParam.getApp_secret());
        Result result = null;
        if (authorize!=null) {
            //1.生成token
            //username为api_app_key_authorizeTenantid
            String token = JwtUtil.sign(CommonConstant.API+"_"+authorize.getAuthorizeTenantid()+"_"+tokenParam.getApp_key(), tokenParam.getApp_secret());
            // 设置token缓存有效时间
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, tokenParam.getTokenTime());
            GetTokenRtn tokenRtn=new GetTokenRtn();
            tokenRtn.setToken(token);
            tokenRtn.setTokenTime(tokenParam.getTokenTime());
            result= Result.OK("token获取成功",tokenRtn);
        } else {
            result = Result.error("token获取失败：访问权限认证未通过");
        }
        return result;
    }
    /**
     * 用户信息同步接口
     *
     * @param userSynParam
     * @param headers
     * @return
     */
    @AutoLog(value = "用户信息同步接口")
    @ApiOperation(value = "用户信息同步接口", notes = "用户信息同步接口",position = 2)
    @PostMapping(value = "/userSyn")
    public Result<JSONObject> userSynApi(@RequestBody UserSynParam userSynParam, @RequestHeader MultiValueMap<String, String> headers) {
        log.info(userSynParam.toString());
        Result result=null;
        String checkerror=null;
        if(StringUtils.isEmpty(userSynParam.getName())){
            checkerror="name值不能为空;";
        }
        if(StringUtils.isEmpty(userSynParam.getPhone_no())){
            checkerror+="phone_no值不能为空;";
        }
        if(StringUtils.isNotEmpty(checkerror)){
            return Result.error("用户添加失败："+checkerror);
        }
        SysUser user=userService.getUserByName(userSynParam.getPhone_no());
        if(user!=null&&user.getId()!=null){
            return Result.error("用户添加失败：该"+user.getUsername()+"手机号已注册，请更换手机号！");
        }else{
            user=new SysUser();
            user.setCreateTime(new Date());//设置创建时间
            user.setPassword(userSynParam.getPhone_no());
            user.setUsername(userSynParam.getPhone_no());
            user.setPhone(userSynParam.getPhone_no());
            user.setRealname(userSynParam.getName());
            String salt = oConvertUtils.randomGen(8);
            user.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
            user.setPassword(passwordEncode);
            user.setStatus(1);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            String relTenantIds = TenantContext.getTenant();
            String selectedDeparts=null;
            if(StringUtils.isNotEmpty(userSynParam.getOrg_name())){
                List<SysDepart> departList=departService.lambdaQuery().eq(SysDepart::getDepartName,userSynParam.getOrg_name())
                        .eq(SysDepart::getTenantId,relTenantIds).list();
                if(departList!=null&&departList.size()==1){
                    selectedDeparts=departList.get(0).getId();
                }
            }
            userService.saveUser(user, null, selectedDeparts, relTenantIds);
            baseCommonService.addLog("添加用户，username： " +user.getUsername() ,CommonConstant.LOG_TYPE_2, 2);
        }
        result = Result.OK("用户添加成功");
        return result;
    }
}
